package com.example.zhilongzhang.constructionpayapp.activity;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.example.zhilongzhang.constructionpayapp.R;
import com.example.zhilongzhang.constructionpayapp.base.App;
import com.example.zhilongzhang.constructionpayapp.base.BaseActivity;
import com.example.zhilongzhang.constructionpayapp.base.ToastManager;
import com.example.zhilongzhang.constructionpayapp.bean.PayStateBean;
import com.example.zhilongzhang.constructionpayapp.bean.StringBean;
import com.example.zhilongzhang.constructionpayapp.http.Bean;
import com.example.zhilongzhang.constructionpayapp.http.HttpMethod;
import com.example.zhilongzhang.constructionpayapp.image.LoweImageView;
import com.example.zhilongzhang.constructionpayapp.method.bluetooth.BluetoothUtil;
import com.example.zhilongzhang.constructionpayapp.method.bluetooth.PrintUtil;
import com.example.zhilongzhang.constructionpayapp.method.bluetooth.ToothMethod;
import com.example.zhilongzhang.constructionpayapp.util.SpUtil;
import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MoneyCodeActivity extends BaseActivity {
    LoweImageView imgCode;
    TextView tvMoney, tvTimeClean;
    private Runnable mRun, mRun2;
    Handler handler = new Handler();
    Handler handler2 = new Handler();
    String base64 = "";
    String address = "";
    boolean isOnClick = false;
    int addTime = 0;
    String errStr="收款成功";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_money_code);
        imgCode = findViewById(R.id.img_code);
        tvMoney = findViewById(R.id.tv_money);
        tvTimeClean = findViewById(R.id.tv_time_clean);
        base64 = getIntent().getStringExtra("qrBase64");
        if (base64 != null) {
            String[] datas = base64.split(",");
            if (datas != null && datas.length > 0) {
                imgCode.setImageBitmap(stringtoBitmap(datas[datas.length - 1]));
            }
        }
        address = getIntent().getStringExtra("address");
        initData();
        Log.e("yong","运行555555");
        setTimer();
        if (getIntent().getStringExtra("born").equals("search")) {
            Log.e("yong","运行333333");
            checkPayStates(SpUtil.getQRPayUrl() + getIntent().getStringExtra("orderId"), getIntent().getStringExtra("orderId"), getIntent().getStringExtra("money"),
                    getIntent().getStringExtra("type"), "", getIntent().getStringExtra("name"), getIntent().getStringExtra("address"), getIntent().getStringExtra("number"), getIntent().getStringExtra("year"), SpUtil.getShopAddUrl());
        } else {
            Log.e("yong","运行444444");
            checkPayStates(SpUtil.getQRPayUrl() + getIntent().getStringExtra("orderId"), getIntent().getStringExtra("orderId"), getIntent().getStringExtra("money"),
                    "", getIntent().getStringExtra("note"), "匿名", "", "", "", "");

        }
    }

    private void initData() {
        tvMoney.setText("收费金额:" + getIntent().getStringExtra("money"));
        findViewById(R.id.left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isOnClick) {
                    return;
                }
                if (handler != null && mRun != null) {
                    handler.removeCallbacks(mRun);
                }
                finish();
            }
        });
        findViewById(R.id.lin_code).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isOnClick) {
                    return;
                }
                startActivity(new Intent(MoneyCodeActivity.this, RecordActivity.class));
            }
        });
    }

    String stTime;

    public void checkState() {
        addTime = addTime + 1;
        if (addTime > 120) {
            ToastManager.getInstance(MoneyCodeActivity.this).showToast("请求失败");
            finish();
            return;
        }
        HttpMethod.checkState(MoneyCodeActivity.this,getIntent().getStringExtra("orderId"),new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                Log.e("abccc","Exception");
            }

            @Override
            public void onResponse(String response) {
                PayStateBean bean = new Gson().fromJson(response, PayStateBean.class);
                stTime ="";
                switch (bean.getState()) {
                    case "OK":
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
                        Date date = new Date(System.currentTimeMillis());
                        stTime=simpleDateFormat.format(date);
                        if (getIntent().getStringExtra("born").equals("search")){
                            if (TextUtils.isEmpty(bean.getCode())){
                                handler.postDelayed(mRun, 5000);
                            }else {
                                if (bean.getCode().equals("1")){
                                    if (SpUtil.getDaYin()) {
                                        setDaYin();
                                    }

                                    ToastManager.getInstance(MoneyCodeActivity.this).showToast("收款成功");
                                    Intent intent = new Intent(MoneyCodeActivity.this, MoneyOKActivity.class);
                                    intent.putExtra("money", getIntent().getStringExtra("money"));
                                    intent.putExtra("address", address);
                                    intent.putExtra("data", stTime);
                                    startActivity(intent);
                                    finish();
                                }else {
                                    if (SpUtil.getDaYin()) {
                                        setDaYin();
                                    }
                                    if (TextUtils.isEmpty(bean.getMsg())){
                                        errStr=bean.getMsg();
                                        ToastManager.getInstance(MoneyCodeActivity.this).showToast(errStr);
                                        finish();
                                    }
                                }
                            }
                        }else {
                            if (SpUtil.getDaYin()) {
                                setDaYin();
                            }
                            ToastManager.getInstance(MoneyCodeActivity.this).showToast("收款成功");
                            Intent intent = new Intent(MoneyCodeActivity.this, MoneyOKActivity.class);
                            intent.putExtra("money", getIntent().getStringExtra("money"));
                            intent.putExtra("address", address);
                            intent.putExtra("data", stTime);
                            startActivity(intent);
                            finish();
                        }
                        break;
                    //失败
                    default:
                        handler.postDelayed(mRun, 5000);
                        break;
                }
            }
        });
    }
    public void printUpdate() {
        HttpMethod.printUpdate(getIntent().getStringExtra("orderId"),new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                Log.e("abccc","Exception");
            }

            @Override
            public void onResponse(String response) {
                StringBean bean = new Gson().fromJson(response, StringBean.class);

            }
        });
    }

    int timeStr = 600;

    private void setTimer() {
        mRun = new Runnable() {
            @Override
            public void run() {
                checkState();
            }
        };

        mRun2 = new Runnable() {
            @Override
            public void run() {
                timeStr = timeStr - 1;
                tvTimeClean.setText("倒计时:" + timeStr + "秒");
                handler2.postDelayed(mRun2, 1000);
            }
        };
        handler2.postDelayed(mRun2, 1000);
        handler.postDelayed(mRun, 5000);
    }

    public Bitmap stringtoBitmap(String string) {
        //将字符串转换成Bitmap类型
        Bitmap bitmap = null;
        try {
            byte[] bitmapArray;
            bitmapArray = Base64.decode(string, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    private void setDaYin() {
        ToothMethod.checkBluetoothState(this);
        connectDevice(ToothMethod.getList(), 2);
    }

    AsyncTask mConnectTask;
    BluetoothSocket mSocket;


    public void connectDevice(BluetoothDevice device, int taskType) {
        if (device != null) {
            mConnectTask = new ConnectBluetoothTask(taskType).execute(device);
        }
    }

    class ConnectBluetoothTask extends AsyncTask<BluetoothDevice, Integer, BluetoothSocket> {

        int mTaskType;

        public ConnectBluetoothTask(int taskType) {
            this.mTaskType = taskType;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected BluetoothSocket doInBackground(BluetoothDevice... params) {
            if (mSocket != null) {
                try {
                    mSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            mSocket = BluetoothUtil.connectDevice(params[0]);

            return mSocket;
        }

        @Override
        protected void onPostExecute(BluetoothSocket socket) {
            if (socket == null || !socket.isConnected()) {
            } else {
                if (getIntent().getStringExtra("born").equals("search")) {
                    PrintUtil.printTest(socket, getIntent().getStringExtra("number"), getIntent().getStringExtra("type"), getIntent().getStringExtra("name"),
                            getIntent().getStringExtra("money"), stTime, getIntent().getStringExtra("orderId"), getIntent().getStringExtra("address"),errStr);
                    printUpdate();
                } else {
                    PrintUtil.printTest2(socket, getIntent().getStringExtra("money"), stTime, getIntent().getStringExtra("orderId"),errStr);
                    printUpdate();
                }
            }

            super.onPostExecute(socket);
        }
    }

    public void checkPayStates(final String url, final String orderId, final String money, final String feetype, final String comments,
                               final String remitterName, final String adress, final String number, final String year, final String depSaveUrl) {
        HttpMethod.checkPayStates(url, orderId, feetype, money, comments, remitterName, adress, number, year, depSaveUrl, new StringCallback() {
            @Override
            public void onError(com.squareup.okhttp.Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                Bean bean = new Gson().fromJson(response, Bean.class);
                switch (bean.code) {
                    case 0:
                        break;
                    case 91:
                        break;
                    default:
                        break;
                }
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
        if (handler != null && mRun != null) {
            handler.removeCallbacks(mRun);
        }
        if (handler2 != null && mRun2 != null) {
            handler2.removeCallbacks(mRun2);
        }
    }
}
